package com.xiongwei.manageback.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiongwei.manageback.constant.Constant;
import com.xiongwei.manageback.DTO.LoginDTO;
import com.xiongwei.manageback.domain.SysUser;
import com.xiongwei.manageback.exception.ServiceException;
import com.xiongwei.manageback.mapper.SysUserMapper;
import com.xiongwei.manageback.service.SysUserService;
import com.xiongwei.manageback.utils.AjaxResult;
import com.xiongwei.manageback.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @ApiOperation("获取个人信息")
    @GetMapping("/getPersonalInformation")
    public AjaxResult register(@RequestParam String username){
        SysUser user = userMapper.getByUsername(username);
        if (ObjectUtil.isNull(user)){
            throw new ServiceException(ServiceException.UN_KNOW_ERROR,"获取个人信息失败");
        }
        return AjaxResult.success(user);
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody LoginDTO loginDTO){
        userService.register(loginDTO);
        return AjaxResult.success();
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginDTO loginDTO){
        return userService.login(loginDTO);
    }

    @ApiOperation("发送验证码")
    @GetMapping("/sendCode")
    public void sendCode(HttpServletResponse response) throws IOException {
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            //定义图形验证码的长、宽、验证码字符数、干扰元素个数
            CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
//            验证码存入缓存用作后续的对比校验
            String captchaCode = captcha.getCode();
            redisTemplate.opsForValue().set(Constant.CAPTCHA_CODE, captchaCode, 2, TimeUnit.MINUTES);
            captcha.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("批量删除用户")
    @PostMapping("/delete/batch")
    public boolean batchDeleteUser(@RequestBody List<Integer> ids) {
        return userService.removeByIds(ids);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/delete/{id}")
    public boolean deleteUser(@PathVariable("id") Integer id) {
        return userService.removeById(id);
    }

    @ApiOperation("新增或修改用户")
    @PostMapping("/addOrUpdateUser")
    public boolean addOrUpdateUser(@RequestBody SysUser user) {
        if (ObjectUtils.isNull(user.getId())) {
            return userService.save(user);
        } else {
//            有id，修改操作
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, user.getId());
            return userService.update(user, wrapper);
        }
    }

    @ApiOperation("用户表分页查询")
    @GetMapping("/list")
    public Page pageQuery(@ApiParam("当前页数") @RequestParam() Integer pageNum,
                          @ApiParam("当前页返回结果数量") @RequestParam() Integer pageSize,
                          @ApiParam("用户名") @RequestParam(required = false, defaultValue = "") String userName) {
        Page<SysUser> users = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>()
                .like(SysUser::getUsername, userName);
        Page<SysUser> userPage = userService.page(users, wrapper);


        return userPage;
    }

}
